﻿using Microsoft.Xna.Framework;

namespace Brain.Ballistics3D
{
    public class Bullet3D
    {
        public Vector3 Direction;
        public Vector3 Position;
        public bool Active;
        public SetBullet3D SetBullet;
        public Ray Ray;
        public RayTestData TestData;
        public BulletManager3D BulletManager;
        public WeaponInfo Weapon;

        public Bullet3D(BulletManager3D manager)
        {
            this.Direction = new Vector3();
            this.Position = new Vector3();
            this.Active = false;
            this.SetBullet = null;
            this.Ray = new Ray();
            this.TestData = new RayTestData();

            this.BulletManager = manager;
        }

        public void Reset(Vector3 direction, Vector3 position,
            WeaponInfo weapon,
            SetBullet3D bullet)
        {
            Active = true;

            SetBullet = bullet;
            Ray = new Ray();
            TestData = new RayTestData();

            this.Direction = direction;
            this.Position = position;
            this.Weapon = weapon;
        }

        public void Update()
        {
            if (Active)
            {
                Position += (Direction * (float)Engine.Instance.GameTime.ElapsedGameTime.TotalSeconds) * Weapon.BulletSpeed;

                // RAY TESTING
                Ray = new Ray(Position, Direction);
                IPhysics3DManager physics = Engine.Instance.Physics3DManager;
                if (physics != null)
                {
                    RayTestData data;
                    if (physics.RayTest(Ray, 1, out data))
                    {
                        // HIT AN OBJECT!
                        SetBullet(this);
                        this.Active = false;
                    }
                }
            }
        }
    }
}
